<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>项目详情 - AI Worker</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 30px 20px;
        }

        .container {
            max-width: 900px;
            margin: 0 auto;
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            color: white;
        }

        .header h1 {
            font-size: 2em;
        }

        .header-buttons {
            display: flex;
            gap: 10px;
            align-items: center;
        }

        .btn-back {
            background: rgba(255,255,255,0.2);
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .btn-back:hover {
            background: rgba(255,255,255,0.3);
        }

        .btn-edit {
            background: rgba(255,255,255,0.2);
            color: white;
            padding: 8px 16px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.3s;
            font-size: 0.9em;
        }

        .btn-edit:hover {
            background: rgba(255,255,255,0.3);
        }

        .btn-edit.editing {
            background: #28a745;
        }

        .main-content {
            background: white;
            border-radius: 15px;
            padding: 40px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        }

        .form-group {
            margin-bottom: 25px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #333;
            font-size: 1em;
        }

        .form-group input[type="text"],
        .form-group textarea {
            width: 100%;
            padding: 12px;
            border: 2px solid #dee2e6;
            border-radius: 8px;
            font-size: 1em;
            transition: border-color 0.3s;
        }

        .form-group input:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #667eea;
        }

        .form-group textarea {
            min-height: 100px;
            resize: vertical;
        }

        .form-group input[type="text"][readonly],
        .form-group textarea[readonly] {
            background: #f8f9fa;
            cursor: not-allowed;
        }

        .help-text {
            font-size: 0.9em;
            color: #666;
            margin-top: 5px;
        }

        .action-buttons {
            display: flex;
            gap: 15px;
            margin-top: 40px;
            padding-top: 30px;
            border-top: 2px solid #e9ecef;
        }

        .btn {
            padding: 14px 30px;
            border: none;
            border-radius: 8px;
            font-size: 1.05em;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            flex: 1;
        }

        .btn-success {
            background: #28a745;
            color: white;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-warning {
            background: #ffc107;
            color: #333;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0,0,0,0.3);
        }

        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .message {
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: none;
        }

        .message.show {
            display: block;
        }

        .message.error {
            background: #f8d7da;
            color: #721c24;
            border-left: 4px solid #dc3545;
        }

        .message.success {
            background: #d4edda;
            color: #155724;
            border-left: 4px solid #28a745;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #999;
        }

        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .radio-group {
            display: flex;
            gap: 15px;
            margin-top: 10px;
        }

        .radio-option {
            flex: 1;
            padding: 12px;
            border: 2px solid #dee2e6;
            border-radius: 8px;
            cursor: not-allowed;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            gap: 8px;
            opacity: 0.7;
        }

        .radio-option.editable {
            cursor: pointer;
            opacity: 1;
        }

        .radio-option.editable:hover {
            border-color: #667eea;
            background: #f8f9fa;
        }

        .radio-option.selected {
            border-color: #667eea;
            background: #e7f1ff;
        }

        .radio-option input[type="radio"] {
            margin: 0;
        }

        .doc-input {
            display: none;
        }

        .doc-input.active {
            display: block;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📋 项目详情</h1>
            <button class="btn-back" onclick="goBack()">← 返回</button>
        </div>

        <div class="main-content">
            <div id="messageBox" class="message"></div>

            <div id="loadingState" class="loading">
                <div class="spinner"></div>
                <p>加载中...</p>
            </div>

            <form id="projectForm" style="display: none;">
                <div class="form-group">
                    <label for="projectName">项目名称</label>
                    <input 
                        type="text" 
                        id="projectName" 
                        name="projectName"
                        placeholder="请输入项目名称"
                    >
                </div>

                <div class="form-group">
                    <label for="projectDescription">项目描述</label>
                    <textarea 
                        id="projectDescription" 
                        name="projectDescription"
                        placeholder="请输入项目描述"
                    ></textarea>
                </div>

                <div class="form-group">
                    <label>需求文档类型</label>
                    <div class="radio-group">
                        <label class="radio-option" id="urlOption" onclick="selectDocType('url')">
                            <input type="radio" name="docType" value="url">
                            <span>📄 飞书文档链接</span>
                        </label>
                        <label class="radio-option" id="fileOption" onclick="selectDocType('file')">
                            <input type="radio" name="docType" value="file">
                            <span>📁 上传Word文档</span>
                        </label>
                    </div>
                </div>

                <div class="form-group doc-input" id="urlInput">
                    <label for="docUrl">飞书文档链接</label>
                    <input 
                        type="text" 
                        id="docUrl" 
                        placeholder="请输入飞书文档的完整URL"
                        readonly
                    >
                </div>

                <div class="form-group doc-input" id="fileInput">
                    <label for="docFile">上传Word文档</label>
                    <input 
                        type="file" 
                        id="docFile" 
                        accept=".doc,.docx"
                    >
                    <div class="help-text">支持.doc和.docx格式，文件大小不超过16MB</div>
                </div>

                <div class="form-group">
                    <label>创建时间</label>
                    <input 
                        type="text" 
                        id="createdAt" 
                        readonly
                    >
                </div>

                <div class="action-buttons">
                    <button type="button" class="btn btn-warning" onclick="toggleEdit()" id="editBtn">
                        ✏️ 编辑
                    </button>
                    <button type="button" class="btn btn-success" onclick="goToTestCases()">
                        📝 生成用例
                    </button>
                    <button type="button" class="btn btn-primary" onclick="goToAnalysis()">
                        🔍 代码分析
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script>
        const projectId = window.location.pathname.split('/')[2];
        let currentProject = null;
        let isEditing = false;

        // 页面加载
        window.onload = function() {
            loadProject();
        };

        // 加载项目
        async function loadProject() {
            try {
                const response = await fetch(`/api/project/${projectId}`);
                if (!response.ok) throw new Error('加载失败');
                
                currentProject = await response.json();
                renderProject();
                
                document.getElementById('loadingState').style.display = 'none';
                document.getElementById('projectForm').style.display = 'block';
            } catch (error) {
                document.getElementById('loadingState').innerHTML = `
                    <p style="color: #dc3545;">加载失败: ${error.message}</p>
                `;
            }
        }

        // 渲染项目
        function renderProject() {
            document.getElementById('projectName').value = currentProject.name || '';
            document.getElementById('projectDescription').value = currentProject.description || '';
            document.getElementById('createdAt').value = new Date(currentProject.created_at).toLocaleString('zh-CN');
            
            // 设置文档类型
            const docType = currentProject.document_type || 'url';
            if (docType === 'url') {
                document.querySelector('input[name="docType"][value="url"]').checked = true;
                document.getElementById('urlOption').classList.add('selected');
                document.getElementById('docUrl').value = currentProject.document_source || '';
                document.getElementById('urlInput').classList.add('active');
            } else {
                document.querySelector('input[name="docType"][value="file"]').checked = true;
                document.getElementById('fileOption').classList.add('selected');
                document.getElementById('fileInput').classList.add('active');
            }
        }

        // 选择文档类型
        function selectDocType(type) {
            if (!isEditing) return; // 非编辑模式不允许切换
            
            // 更新选中状态
            document.getElementById('urlOption').classList.remove('selected');
            document.getElementById('fileOption').classList.remove('selected');
            document.getElementById('urlInput').classList.remove('active');
            document.getElementById('fileInput').classList.remove('active');
            
            if (type === 'url') {
                document.getElementById('urlOption').classList.add('selected');
                document.getElementById('urlInput').classList.add('active');
                document.querySelector('input[name="docType"][value="url"]').checked = true;
            } else {
                document.getElementById('fileOption').classList.add('selected');
                document.getElementById('fileInput').classList.add('active');
                document.querySelector('input[name="docType"][value="file"]').checked = true;
            }
        }

        // 切换编辑模式
        function toggleEdit() {
            isEditing = !isEditing;
            const nameInput = document.getElementById('projectName');
            const descInput = document.getElementById('projectDescription');
            const docUrlInput = document.getElementById('docUrl');
            const editBtn = document.getElementById('editBtn');
            
            if (isEditing) {
                nameInput.readOnly = false;
                descInput.readOnly = false;
                docUrlInput.readOnly = false;
                nameInput.focus();
                editBtn.innerHTML = '💾 保存';
                editBtn.className = 'btn btn-success';
            } else {
                saveProject();
            }
        }

        // 保存项目
        async function saveProject() {
            const name = document.getElementById('projectName').value.trim();
            const description = document.getElementById('projectDescription').value.trim();
            const docType = document.querySelector('input[name="docType"]:checked').value;
            const docUrl = document.getElementById('docUrl').value.trim();
            const docFile = document.getElementById('docFile').files[0];
            
            if (!name) {
                showMessage('项目名称不能为空', 'error');
                return;
            }
            
            try {
                let documentSource = currentProject.document_source;
                let documentType = currentProject.document_type;
                
                // 如果选择了URL类型且URL有变化
                if (docType === 'url' && docUrl && docUrl !== currentProject.document_source) {
                    documentSource = docUrl;
                    documentType = 'url';
                }
                // 如果选择了文件类型且有上传新文件
                else if (docType === 'file' && docFile) {
                    // 上传文件
                    const formData = new FormData();
                    formData.append('file', docFile);
                    
                    const uploadRes = await fetch('/api/upload', {
                        method: 'POST',
                        body: formData
                    });
                    
                    const uploadData = await uploadRes.json();
                    if (!uploadData.success) throw new Error('文件上传失败');
                    
                    documentSource = uploadData.file_path;
                    documentType = 'file';
                }
                
                const response = await fetch(`/api/project/${projectId}`, {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ 
                        name, 
                        description,
                        document_source: documentSource,
                        document_type: documentType
                    })
                });
                
                if (!response.ok) throw new Error('保存失败');
                
                currentProject = await response.json();
                isEditing = false;
                renderProject();
                
                // 退出编辑模式
                document.getElementById('projectName').readOnly = true;
                document.getElementById('projectDescription').readOnly = true;
                document.getElementById('docUrl').readOnly = true;
                document.getElementById('editBtn').innerHTML = '✏️ 编辑';
                document.getElementById('editBtn').className = 'btn btn-warning';
                
                showMessage('保存成功！', 'success');
            } catch (error) {
                showMessage('保存失败: ' + error.message, 'error');
            }
        }

        // 跳转到测试用例
        function goToTestCases() {
            window.location.href = `/project/${projectId}/testcases`;
        }

        // 跳转到代码分析
        function goToAnalysis() {
            window.location.href = `/project/${projectId}/analysis`;
        }

        // 返回
        function goBack() {
            window.location.href = '/';
        }

        // 显示消息
        function showMessage(message, type) {
            const box = document.getElementById('messageBox');
            box.textContent = message;
            box.className = `message ${type} show`;
            
            setTimeout(() => {
                box.classList.remove('show');
            }, type === 'success' ? 3000 : 5000);
        }
    </script>
</body>
</html>
